package com.itown.expo.helper;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.criterion.DetachedCriteria;

import webframe.common.dao.Pagination;
import webframe.common.helper.ControllerHelper;

import com.itown.expo.model.Decl;
import com.itown.expo.model.Goods;
import com.itown.expo.model.MainDeclGoods;
import com.itown.expo.model.MainGoodsDecl;
import com.itown.expo.model.NormalDeclGoods;
import com.itown.expo.model.NormalGoodsDecl;

public class MyControllerHelper extends ControllerHelper {
	private static long OVERRUN_TIME = 1000l * 60 * 60 * 24 * 31 * 6; // six_months

	public static DetachedCriteria getDeclDetachedCriteria(Decl decl) {
		DetachedCriteria criteria = null;
		String type = decl.getType();
		if (type == null || type.length() == 0) {
			criteria = DetachedCriteria.forClass(Decl.class, "d");
		} else if (type.equals("A")) {
			criteria = DetachedCriteria.forClass(NormalGoodsDecl.class, "d");
		} else if (type.equals("B")) {
			criteria = DetachedCriteria.forClass(MainGoodsDecl.class, "d");
		}
		return criteria;
	}

	public static DetachedCriteria getGoodsDetachedCriteria(Goods goods) {
		DetachedCriteria criteria = null;
		String type = goods.getType();
		if (type == null || type.length() == 0) {
			criteria = DetachedCriteria.forClass(Goods.class, "g");
		} else if (type.equals("A")) {
			criteria = DetachedCriteria.forClass(NormalDeclGoods.class, "g");
		} else if (type.equals("B")) {
			criteria = DetachedCriteria.forClass(MainDeclGoods.class, "g");
		}
		return criteria;
	}

	public static Pagination<MainGoodsDecl> judgeOverrun(
			Pagination<MainGoodsDecl> page) {
		Collection<MainGoodsDecl> coll = page.getItems();
		Date now = DateUtils.truncate(new Date(), Calendar.DATE);

		for (MainGoodsDecl decl : coll) {
			Date declDate = DateUtils.truncate(decl.getDeclDate(),
					Calendar.DATE);
			if (now.getTime() - declDate.getTime() > OVERRUN_TIME) {
				decl.getMap().put("overrun", true);
			}
		}
		return page;
	}
}
